import React, { useState, useRef, useEffect } from 'react';
import { Code2, Copy, RotateCcw, Eye, Edit3 } from 'lucide-react';

interface ResultEditorProps {
  content: string;
  onChange: (content: string) => void;
  onSave?: (content: string) => void;
}

export default function ResultEditor({ content, onChange }: ResultEditorProps) {
  const [localContent, setLocalContent] = useState(content);
  const [activeTab, setActiveTab] = useState<'preview' | 'raw' | 'edit'>('preview');
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    setLocalContent(content);
  }, [content]);

  const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newContent = e.target.value;
    setLocalContent(newContent);
    onChange(newContent);
  };

  // 格式化内容为HTML显示（Markdown渲染预览）
  const formatContentAsHtml = () => {
    // 增强的Markdown格式化
    let html = localContent
      // 标题
      .replace(/^# (.*$)/gm, '<h1 class="text-2xl font-bold mt-4 mb-2 text-gray-900">$1</h1>')
      .replace(/^## (.*$)/gm, '<h2 class="text-xl font-bold mt-3 mb-1 text-gray-800">$1</h2>')
      .replace(/^### (.*$)/gm, '<h3 class="text-lg font-bold mt-2 mb-1 text-gray-700">$1</h3>')
      .replace(/^#### (.*$)/gm, '<h4 class="text-base font-bold mt-2 mb-1 text-gray-700">$1</h4>')
      .replace(/^##### (.*$)/gm, '<h5 class="text-sm font-bold mt-1 mb-1 text-gray-600">$1</h5>')
      .replace(/^###### (.*$)/gm, '<h6 class="text-xs font-bold mt-1 mb-1 text-gray-600">$1</h6>')
      // 样式
      .replace(/\*\*(.*?)\*\*/g, '<strong class="font-bold">$1</strong>')
      .replace(/\*(.*?)\*/g, '<em class="italic">$1</em>')
      .replace(/__(.*?)__/g, '<u class="underline">$1</u>')
      .replace(/`(.*?)`/g, '<code class="bg-gray-100 px-1 py-0.5 rounded text-sm font-mono">$1</code>')
      // 列表
      .replace(/^- (.*$)/gm, '<li class="list-disc ml-6 mb-1">$1</li>')
      .replace(/^\* (.*$)/gm, '<li class="list-disc ml-6 mb-1">$1</li>')
      .replace(/^[0-9]+\. (.*$)/gm, '<li class="list-decimal ml-6 mb-1">$1</li>')
      // 引用
      .replace(/^> (.*$)/gm, '<blockquote class="border-l-4 border-gray-300 pl-4 my-2 italic text-gray-600">$1</blockquote>')
      // 代码块
      .replace(/```([\s\S]*?)```/g, '<pre class="bg-gray-100 p-4 rounded-lg overflow-x-auto my-2"><code class="text-sm font-mono">$1</code></pre>')
      // 链接和图片
      .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="text-blue-600 hover:text-blue-800 underline">$1</a>')
      .replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" class="max-w-full h-auto rounded my-2" />')
      // 表格
      .replace(/\n\|(.+)\|\n\|[-:\| ]+\|\n((?:\|.+\|\n)*)/g, (_match, header, rows) => {
        const headers = header.split('|').filter((h: string) => h.trim()).map((h: string) => `<th class="border px-4 py-2 text-left font-bold">${h.trim()}</th>`).join('');
        const tableRows = rows.split('\n').filter((r: string) => r.trim()).map((row: string) => {
          const cells = row.split('|').filter((c: string) => c.trim()).map((c: string) => `<td class="border px-4 py-2">${c.trim()}</td>`).join('');
          return `<tr>${cells}</tr>`;
        }).join('');
        return `<table class="border-collapse border border-gray-300 my-2"><thead><tr>${headers}</tr></thead><tbody>${tableRows}</tbody></table>`;
      });
    
    // 处理段落和换行
    html = html.replace(/\n/g, '<br>');
    html = html.replace(/<br><br>/g, '</p><p class="mb-2">');
    html = `<div class="prose max-w-none">${html}</div>`;
    
    return html;
  };

  // 复制内容
  const copyContent = () => {
    navigator.clipboard.writeText(localContent);
  };

  // 重置内容
  const resetContent = () => {
    setLocalContent(content);
    onChange(content);
  };

  return (
    <div className="flex-1 flex flex-col overflow-hidden bg-white">
      {/* Tab导航栏 */}
      <div className="border-b border-gray-200 bg-gray-50">
        <div className="flex justify-between items-center">
          <div className="flex">
            <button
              className={`flex items-center px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'preview'
                  ? 'border-blue-500 text-blue-600 bg-white'
                  : 'border-transparent text-gray-600 hover:text-gray-800 hover:bg-gray-100'
              }`}
              onClick={() => setActiveTab('preview')}
            >
              <Eye className="w-4 h-4 mr-2" />
              预览
            </button>
            <button
              className={`flex items-center px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'raw'
                  ? 'border-blue-500 text-blue-600 bg-white'
                  : 'border-transparent text-gray-600 hover:text-gray-800 hover:bg-gray-100'
              }`}
              onClick={() => setActiveTab('raw')}
            >
              <Code2 className="w-4 h-4 mr-2" />
              原始文本
            </button>
            <button
              className={`flex items-center px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'edit'
                  ? 'border-blue-500 text-blue-600 bg-white'
                  : 'border-transparent text-gray-600 hover:text-gray-800 hover:bg-gray-100'
              }`}
              onClick={() => setActiveTab('edit')}
            >
              <Edit3 className="w-4 h-4 mr-2" />
              编辑
            </button>
          </div>
          
          {/* 编辑模式下的操作按钮 */}
          {activeTab === 'edit' && (
            <div className="flex items-center space-x-2 px-4">
              <button
                onClick={copyContent}
                className="p-2 text-gray-600 hover:bg-gray-200 rounded"
                title="复制内容"
              >
                <Copy className="w-4 h-4" />
              </button>
              <button
                onClick={resetContent}
                className="p-2 text-gray-600 hover:bg-gray-200 rounded"
                title="重置内容"
              >
                <RotateCcw className="w-4 h-4" />
              </button>
            </div>
          )}
        </div>
      </div>
      
      {/* 内容区域 */}
      <div className="flex-1 overflow-hidden">
        {activeTab === 'preview' && (
          <div className="h-full overflow-auto">
            <div className="p-4">
              <div 
                className="prose max-w-none"
                dangerouslySetInnerHTML={{ __html: formatContentAsHtml() }}
              />
            </div>
          </div>
        )}
        
        {activeTab === 'raw' && (
          <div className="h-full overflow-auto">
            <div className="p-4 h-full">
              <pre className="bg-gray-50 p-4 rounded-lg text-sm font-mono whitespace-pre-wrap break-words h-full overflow-auto">
                {localContent}
              </pre>
            </div>
          </div>
        )}
        
        {activeTab === 'edit' && (
          <div className="h-full flex flex-col">
            <div className="flex-1 p-4">
              <textarea
                ref={textareaRef}
                value={localContent}
                onChange={handleContentChange}
                className="w-full h-full p-4 bg-white border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none font-mono text-sm"
                placeholder="在这里编辑markdown内容..."
                style={{ minHeight: '400px' }}
              />
            </div>
            <div className="bg-gray-50 border-t border-gray-200 px-4 py-2 text-xs text-gray-500">
              支持Markdown语法：标题、粗体、斜体、列表、链接、图片、代码块等
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
